package com.chinacreator.galaxylive.wx.web.rest;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.chinacreator.galaxylive.wx.WxService;

/**
 * 微信回调使用接口
 */
@Path("/galaxy/v1/wxs")
@Produces({MediaType.APPLICATION_JSON })
@Consumes({MediaType.APPLICATION_JSON })
@Controller
public class WxResource {

    @Autowired
    private WxService wxService;

    @Context
    private HttpServletRequest request;
    @Context
    private HttpServletResponse response;

    @GET
    @Path("/oauth2_redirect")
    public void oauth2Redirect(@QueryParam("code") String code, @QueryParam("state") String state,@QueryParam("redirect") String redirect){
        try {
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxService.oauth2getAccessToken(code);
            String scope = wxMpOAuth2AccessToken.getScope();
            WxMpUser wxMpUser = null;
            if(WxConsts.OAuth2Scope.SNSAPI_USERINFO.equals(scope)){
                wxMpUser = wxService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
            }else {
                wxMpUser = new WxMpUser();
                wxMpUser.setOpenId(wxMpOAuth2AccessToken.getOpenId());
            }
            
            if(state.indexOf("^") > -1){
            	state = state.replace("^", "&");
            	redirect = redirect+"?"+state;
            }else if(null != state && !"".equals(state)){
            	redirect = redirect+"?"+state;
            }

            wxService.setWxMpUser(request,wxMpUser);
            response.sendRedirect(redirect);
        } catch (WxErrorException | IOException e) {
            e.printStackTrace();
        }
    }
}
